package com.xkw.autocode.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class MyDateUtils {

	private static final String TIME_SEPARATE1 = " - ";
	
	private static final String TIME_SEPARATE2 = " ~ ";
	
	public static final String TIME_FORMAT1 = "yyyy-MM-dd HH:mm:ss";
	public static final String TIME_FORMAT2 = "yyyy/MM/dd HH:mm:ss";
	public static final String DATA_FORMAT1 = "yyyy-MM-dd";
	public static final String DATA_FORMAT2 = "yyyy/MM/dd";
	
	/**
	 * 获取开始时间和结束时间的数组
	 * @param timeString，格式：	2018/10/04 - 2018/10/31
	 * @return
	 */
	public static Long[] getStartAndEndTime(String timeString) {
		if(timeString == null || timeString.length() == 0) {
			return null;
		}
		
		String[] timeArray = null;
		if(timeString.indexOf(TIME_SEPARATE1) != -1) {
			timeArray = timeString.split(TIME_SEPARATE1);
		}else if(timeString.indexOf(TIME_SEPARATE2) != -1) {
			timeArray = timeString.split(TIME_SEPARATE2);
		}else {
			return null;
		}

		if (timeArray != null && timeArray.length == 2) {
			
			DateFormat format =  new SimpleDateFormat(TIME_FORMAT1);
			
			try {
				Long startTime = format.parse(timeArray[0].replaceAll("/", "-") + " 00:00:00").getTime();
				Long endTime = format.parse(timeArray[1].replaceAll("/", "-") + " 23:59:59").getTime();

				Long[] times = { startTime, endTime };
				
				return times;
			} catch (ParseException e) {
				e.printStackTrace();
			}
			
			return null;
		}
		
		return null;
	}
	
	public static String formatDateTime(String pattern, long time) {
		return formatDateTime(pattern, new Date(time));
	}
    public static String formatDateTime(String pattern, Date date) {
    	if (date == null) return "";
    	
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);

        return dateFormat.format(date);
    }
    
    public static Date parseTime(String format,String date){
		
		if(date == null) {
			return null;
		}
		
		Date returnDate = null;
		DateFormat df = new SimpleDateFormat(format);
		try {
			returnDate = df.parse(date);
		} catch (ParseException e) {
			return null;
		}
		return returnDate;
	}
    
	/**
	 * 获取日初时间
	 * @param dataTime
	 * @return
	 */
	public static long getStartDateTime(long dataTime) {
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(dataTime);
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		c.set(Calendar.MILLISECOND, 0);
		return c.getTimeInMillis();
	}
	
	/**
	 * 获取日终时间
	 * @param dataTime
	 * @return
	 */
	public static long getEndDateTime(long dataTime) {
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(dataTime);
		c.set(Calendar.HOUR_OF_DAY, 23);
		c.set(Calendar.MINUTE, 59);
		c.set(Calendar.SECOND, 59);
		c.set(Calendar.MILLISECOND, 0);
		return c.getTimeInMillis();
	}
}
